package com.hxkcloud.nurse.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.activitys.MessageMainActivity;
import com.hxkcloud.nurse.activitys.NewsActivity;
import com.hxkcloud.nurse.activitys.QRcodeScanActivity;
import com.hxkcloud.nurse.adapter.DiscoverPatientFragmentAdapter;
import com.hxkcloud.nurse.beans.DepartmentIndexInfo;
import com.hxkcloud.nurse.beans.DoctorGroupBean;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.ImageOptionUtils;
import com.hxkcloud.nurse.utils.ImageUtil;
import com.hxkcloud.nurse.utils.StringUtil;
import com.hxkcloud.nurse.views.CircleImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-07-06.
 * Description:护士发现模块
 */
public class DiscoverFragment extends BaseFragment implements View.OnClickListener, DiscoverPatientFragment.discoverPatientRefreshListener, SwipeRefreshLayout.OnRefreshListener {

    private View view;
    private LinearLayout ll_empty;//没有科室数据时显示，头部可以扫描二维码
    private LinearLayout ll_ttitle;
    private ImageView iv_qrcode;
    private TextView tv_title;
    private ImageView iv_tmessage;

    private LinearLayout ll_info;//展示科室信息

    private LinearLayout ll_title;
    private ImageView iv_message;
    private ImageView iv_msgpoint;
    private RelativeLayout rl_head;
    private CircleImageView civ_head;
    private ImageView iv_vip;
    private TextView tv_name;
    private LinearLayout ll_tags;

    private AppBarLayout appbar;
    private LinearLayout ll_departmentintro;
    private TextView tv_introup;
    private ImageView iv_introup;
    private TextView tv_introduce;

    private LinearLayout ll_course;
    private LinearLayout ll_news;

    private LinearLayout ll_notmanage;
    private TextView tv_notmanage;
    private View view_notmanage;
    private LinearLayout ll_ismanage;
    private TextView tv_ismanage;
    private View view_ismanage;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ViewPager vp_patients;

    private FragmentManager fragmentManager;
    private DiscoverPatientFragment patient1Fragment;
    private DiscoverPatientFragment patient2Fragment;
    private DiscoverPatientFragmentAdapter patientAdapter;
    private List<DiscoverPatientFragment> patientFragments;

    private boolean introup = false;//是否展示介绍
    private int patientType = 0;//0未管理 1已管理

    private DepartmentIndexInfo departmentInfo;

    private TextView msg_number;
    private boolean showIcon;

    public DiscoverFragment(){
        super();
    }

    public void showPoint(boolean show) {
        if (iv_msgpoint==null)
            return;
        showIcon = show;
        if (show) {
            iv_msgpoint.setVisibility(View.VISIBLE);
        } else {
            iv_msgpoint.setVisibility(View.INVISIBLE);
        }
        YjhApplication.getInstance().showMsg(msg_number);
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_GETDEPARTMENTINDEXINFO_SUCCESS:
                swipeRefreshLayout.setRefreshing(false);
                if (msg.obj != null) {
                    departmentInfo = (DepartmentIndexInfo) msg.obj;
                    showData();
                    return;
                } else {
                    toastMsg(R.string.departmentinfogetfail);
                }

                break;
            case MessageCode.NETWORKCODE_GETDEPARTMENTINDEXINFO_FAILURE:
                swipeRefreshLayout.setRefreshing(false);
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.departmentinfogetfail);
                }

                break;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_discover1, container, false);
        initView();
        initListener();
//        initData();
        return view;
    }

    @Override
    protected void initView() {
        ll_empty = (LinearLayout) view.findViewById(R.id.ll_discover_empty);
        ll_ttitle = (LinearLayout) view.findViewById(R.id.ll_title);
        iv_qrcode = (ImageView) view.findViewById(R.id.iv_title_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title_title);
        iv_tmessage = (ImageView) view.findViewById(R.id.iv_title_func);

        ll_info = (LinearLayout) view.findViewById(R.id.ll_discover_info);

        msg_number = (TextView) view.findViewById(R.id.msg_home_number);

        ll_title = (LinearLayout) view.findViewById(R.id.ll_discover_title);
        iv_message = (ImageView) view.findViewById(R.id.iv_discover_message);
        iv_msgpoint = (ImageView) view.findViewById(R.id.iv_discover_point);
        rl_head = (RelativeLayout) view.findViewById(R.id.rl_discover_head);
        civ_head = (CircleImageView) view.findViewById(R.id.civ_discover_head);
        iv_vip = (ImageView) view.findViewById(R.id.iv_discover_vip);
        tv_name = (TextView) view.findViewById(R.id.tv_discover_name);
        ll_tags = (LinearLayout) view.findViewById(R.id.ll_discover_tags);

        appbar = (AppBarLayout) view.findViewById(R.id.appbar_discover);
        ll_departmentintro = (LinearLayout) view.findViewById(R.id.ll_discover_departmentintro);
        tv_introup = (TextView) view.findViewById(R.id.tv_discover_introup);
        iv_introup = (ImageView) view.findViewById(R.id.iv_discover_introup);
        tv_introduce = (TextView) view.findViewById(R.id.tv_discover_indruduce);

        ll_course = (LinearLayout) view.findViewById(R.id.ll_discover_course);
        ll_news = (LinearLayout) view.findViewById(R.id.ll_discover_news);

        ll_notmanage = (LinearLayout) view.findViewById(R.id.ll_discover_notmanage);
        tv_notmanage = (TextView) view.findViewById(R.id.tv_discover_notmanage);
        view_notmanage = view.findViewById(R.id.view_discover_notmanage);
        ll_ismanage = (LinearLayout) view.findViewById(R.id.ll_discover_ismanage);
        tv_ismanage = (TextView) view.findViewById(R.id.tv_discover_ismanage);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh_discover);
        view_ismanage = view.findViewById(R.id.view_discover_ismanage);
        vp_patients = (ViewPager) view.findViewById(R.id.viewpager_discover_patient);

        ll_empty.setVisibility(View.GONE);
        setTitlePadding(ll_ttitle);
//        iv_qrcode.setImageResource(R.drawable.qrcode);
        tv_title.setText(getResources().getString(R.string.discover));
        iv_tmessage.setImageResource(R.drawable.nav_message);

        ll_info.setVisibility(View.VISIBLE);

        setTitlePadding(ll_title);

        LinearLayout.LayoutParams lp_headl = new LinearLayout.LayoutParams(screenWidth / 4, screenWidth / 4);
        rl_head.setLayoutParams(lp_headl);
        RelativeLayout.LayoutParams lp_head = new RelativeLayout.LayoutParams(screenWidth / 4, screenWidth / 4);
        civ_head.setLayoutParams(lp_head);
        RelativeLayout.LayoutParams lp_vip = new RelativeLayout.LayoutParams(screenWidth / 12, screenWidth / 12);
        lp_vip.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        lp_vip.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        lp_vip.rightMargin = ImageUtil.dip2px(5, mContext);
        lp_vip.bottomMargin = ImageUtil.dip2px(5, mContext);
        iv_vip.setLayoutParams(lp_vip);

        fragmentManager = getChildFragmentManager(); //((FragmentActivity) mContext).getSupportFragmentManager();
        patient1Fragment = new DiscoverPatientFragment(0);
        patient1Fragment.setRefreshListener(this);
        patient2Fragment = new DiscoverPatientFragment(1);
        patient2Fragment.setRefreshListener(this);
        patientFragments = new ArrayList<>();
        patientFragments.add(patient1Fragment);
        patientFragments.add(patient2Fragment);
        patientAdapter = new DiscoverPatientFragmentAdapter(fragmentManager, patientFragments);
        vp_patients.setAdapter(patientAdapter);
        vp_patients.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    tv_notmanage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    view_notmanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_ismanage.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
                    view_ismanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));
                    patientType = 0;
                } else {
                    tv_notmanage.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
                    view_notmanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));
                    tv_ismanage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    view_ismanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    patientType = 1;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        swipeRefreshLayout.setEnabled(true);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setProgressViewOffset(true, -20, 100);
        if (showIcon) {
            iv_msgpoint.setVisibility(View.VISIBLE);
        } else {
            iv_msgpoint.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void initListener() {
        iv_qrcode.setOnClickListener(this);
        iv_tmessage.setOnClickListener(this);
        iv_message.setOnClickListener(this);
        ll_departmentintro.setOnClickListener(this);
        ll_course.setOnClickListener(this);
        ll_news.setOnClickListener(this);
        ll_notmanage.setOnClickListener(this);
        ll_ismanage.setOnClickListener(this);

        //appbar是否显示 的监听，用来控制列表是否可以刷新
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (patientAdapter != null) {
                    if (verticalOffset >= 0) {
//                        if (imageHandler != null)
//                            imageHandler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                        patientAdapter.getItem(patientType).setRefreshble(true, 0);

                    } else if (verticalOffset <= -appBarLayout.getMeasuredHeight()) {
//                        if (imageHandler != null)
//                            imageHandler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                        patientAdapter.getItem(patientType).setRefreshble(true, 1);
                    } else {
                        patientAdapter.getItem(patientType).setRefreshble(false, 0);
                    }
                }

                if (verticalOffset >= 0) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    swipeRefreshLayout.setEnabled(false);
                }
            }
        });
    }

    @Override
    protected void initData() {

        loading();
        YiJiaHuNetWorkUtils.getDepartmentIndexInfo(loginInfo.getDepartmentId(), handler);


    }

    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(loginInfo.getDepartmentId())) {
            ll_empty.setVisibility(View.VISIBLE);
            ll_info.setVisibility(View.GONE);
        } else {
            if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                if (departmentInfo == null) {
                    initData();
                }
            }
            ll_empty.setVisibility(View.GONE);
            ll_info.setVisibility(View.VISIBLE);
        }
        YjhApplication.getInstance().showMsg(msg_number);

    }

    //展示接口数据
    private void showData() {
        if (departmentInfo != null) {
            imageLoader.displayImage(departmentInfo.getHeadImg(), civ_head, ImageOptionUtils.getInstance().getDepartmentHeadOptions());
            civ_head.setBorderColorResource(R.color.light_blue_border);
            civ_head.setBorderWidth(5);

            if (departmentInfo.getIsVip().equals("0")) {
                iv_vip.setVisibility(View.VISIBLE);
            } else {
                iv_vip.setVisibility(View.INVISIBLE);
            }
            tv_name.setText(departmentInfo.getTitle());
            LinearLayout.LayoutParams lp_tag = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp_tag.setMargins(5, 0, 5, 0);
            if (departmentInfo.getTags() != null && departmentInfo.getTags().size() > 0) {
                ll_tags.removeAllViews();
                for (int i = 0; i < Math.min(4, departmentInfo.getTags().size()); i++) {
                    String tag = departmentInfo.getTags().get(i);
                    TextView tv_tag1 = new TextView(mContext);
                    tv_tag1.setLayoutParams(lp_tag);
                    tv_tag1.setSingleLine(true);
                    tv_tag1.setMaxLines(1);
                    tv_tag1.setEllipsize(TextUtils.TruncateAt.END);
                    tv_tag1.setBackgroundResource(R.drawable.foundation_whitecorneralpha);
                    tv_tag1.setTextColor(Color.WHITE);
                    tv_tag1.setPadding(15, 10, 15, 10);
                    tv_tag1.setText(tag);
                    tv_tag1.setTextSize(12);
                    tv_tag1.setGravity(Gravity.CENTER);
                    ll_tags.addView(tv_tag1);
                }
            }
            tv_introduce.setText(StringUtil.ToDBC(departmentInfo.getIntro()));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                Intent iQR = new Intent(mContext, QRcodeScanActivity.class);
                startActivity(iQR);
                break;
            case R.id.iv_title_func:
            case R.id.iv_discover_message:
                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                    Intent iM = new Intent(mContext, MessageMainActivity.class);
                    startActivity(iM);
                } else {
                    toastMsg(R.string.pleasefirstjoindepartment);
                }
                break;
            case R.id.ll_discover_departmentintro:
                if (introup) {
                    tv_introup.setText(R.string.packup);
                    iv_introup.setImageResource(R.drawable.list_expand_pre);
                    tv_introduce.setVisibility(View.VISIBLE);
                    introup = false;
                } else {
                    tv_introup.setText(R.string.packdown);
                    iv_introup.setImageResource(R.drawable.list_expand);
                    tv_introduce.setVisibility(View.GONE);
                    introup = true;
                }
                break;
            case R.id.ll_discover_notmanage:
                if (patientType == 1) {
                    tv_notmanage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    view_notmanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    tv_ismanage.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
                    view_ismanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));
                    vp_patients.setCurrentItem(0);
                    patientType = 0;
                }
                break;
            case R.id.ll_discover_ismanage:
                if (patientType == 0) {
                    tv_notmanage.setTextColor(ContextCompat.getColor(mContext, R.color.black_text));
                    view_notmanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));
                    tv_ismanage.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    view_ismanage.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_blue));
                    vp_patients.setCurrentItem(1);
                    patientType = 1;
                }
                break;
            case R.id.ll_discover_news:
                Intent newsIntent = new Intent(getActivity(), NewsActivity.class);
                newsIntent.putExtra("type", YjhApplication.articlekind_news);
                startActivity(newsIntent);
                break;
            case R.id.ll_discover_course:
                Intent courseIntent = new Intent(getActivity(), NewsActivity.class);
                courseIntent.putExtra("type", YjhApplication.articlekind_course);
                startActivity(courseIntent);

                break;
        }
    }

    @Override
    public void onRefresh() {
        loading();
        YiJiaHuNetWorkUtils.getDepartmentIndexInfo(loginInfo.getDepartmentId(), handler);
        if (vp_patients.getCurrentItem() == 0) {
            patient1Fragment.refresh();
        }
        if (vp_patients.getCurrentItem() == 1) {
            patient2Fragment.refresh();
        }
    }

    @Override
    public void onAllRefresh() {
        if (patient1Fragment != null) {
            patient1Fragment.refresh();
        }
        if (patient2Fragment != null) {
            patient2Fragment.refresh();
        }
    }

    public void setDoctorGroup(List<DoctorGroupBean> groups) {
        if (groups != null && groups.size() > 0) {
            patient1Fragment.setDoctorGroup(groups);
        }
    }

    public static DiscoverFragment newInstance(){

        return new DiscoverFragment();
    }

}
